/*
*	Copyright (c) 2009 Brent Mombourquette
*
*	Permission is hereby granted, free of charge, to any person
*	obtaining a copy of this software and associated documentation
*	files (the "Software"), to deal in the Software without
*	restriction, including without limitation the rights to use,
*	copy, modify, merge, publish, distribute, sublicense, and/or sell
*	copies of the Software, and to permit persons to whom the
*	Software is furnished to do so, subject to the following
*	conditions:
*
*	The above copyright notice and this permission notice shall be
*	included in all copies or substantial portions of the Software.
*
*	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
*	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
*	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
*	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
*	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
*	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*	OTHER DEALINGS IN THE SOFTWARE.
*
*	This file contains the functions which log each visited URL and the accompanying information.
*/
// Import a referrence to the BreadCrumbs database
Components.utils.import("resource://BreadCrumbs/database.jsm");

var first = true;					// 
var on = false;						// Signifies whether the logging feature is on or off

var sorURL = 'EMPTY_SOURCE_ENTRY';	// The last URL; the source URL (By default there is no "last" URL, so it is set to EMPTY_SOURCE_ENTRY
var destURL;						// The URL of the current website ; the destination URL

var logData = {
	/*
	 * Enters the current values of destURL and sorURL as a new entry in the database.
	 * Globals: destURL, first, realTimeUpdate() [from util.js], sorURL
	 * @param {Document} doc		The document reference of the website to be logged
	 * @param {Window} win		The window that needs to be logged (may be a tab's content window)
	 */
    log: function(doc, win) {
		var title = doc.title.split(" - Mozilla Firefox"); // Every title contains " - Mozilla Firefox" so it might as well be removed
		if (title == "")
			title = "No Title";
			
		var linkType = logHelper.extractLinkType(doc);
		
		if (!logHelper.isUnique(destURL, sorURL)) { // sorURL is always updated so that the next entry in the database has the proper source
			sorURL = destURL;
			return;
		}
		
		var fav;
		try {
			var faviconURI = gBrowser.mFaviconService.getFaviconForPage(doc.baseURIObject);
			fav = faviconURI.spec;
		} catch (ex) { // An exception means that getFaviconForPage failed, so use my custom favicon extraction methods.
			fav = logHelper.extractExplicitFavURL(doc);
		}
		
		var img = logHelper.extractThumbnail(win);
		
		if (first) { // First entry has no source
			sorURL = 'EMPTY_SOURCE_ENTRY';
			first = false;
		}
		
		// Safeguard: This solves a bug within the onload event that fires it multiple times, along with preventing the logging of "about:blank" pages
		// Sometimes the user may click too fast, so adding another check to ensure the destURL is unique is required
		if (destURL == sorURL || destURL == 'about:blank' || !logHelper.isUnique(destURL, sorURL))
			return;			
			
		var addURLString = "INSERT INTO edgeLog (row,destination,source,title,annotation,fav,permTitle,linkType,image,cords) VALUES (NULL,?1,?2,?3,'Right Click to Annotate.',?4,?5,?6,?7,'NO_CORDS');";
		var addURLStatement = breadcrumbsDBConn.createStatement(addURLString);
		
			
		addURLStatement.bindUTF8StringParameter(0, destURL);
		addURLStatement.bindUTF8StringParameter(1, sorURL);
		addURLStatement.bindUTF8StringParameter(2, title[0]);
		addURLStatement.bindUTF8StringParameter(3, fav);
		addURLStatement.bindUTF8StringParameter(4, title[0]);
		addURLStatement.bindUTF8StringParameter(5, linkType);
		addURLStatement.bindUTF8StringParameter(6, img);
		addURLStatement.execute()
		addURLStatement.reset();
		addURLStatement.finalize();
		
		try { // Attempt to update the graph from graph_page.html
			realTimeUpdate();
		} catch (ex) {} // This means graph_page.html is not open
		
		sorURL = destURL;
    },
	
	/*
	 * Maintain the sorURL and trail of sites when the user creates and/or cycles through tabs.
	 * Globals: destURL, on, sorURL
	 */
	tabChange: function() {
		var tab = gBrowser.selectedTab.linkedBrowser;
		// A new tab isn't neccesarily loaded so the onload event does not fire, thus 
		// sorURL has to be manually set
		if (tab.contentDocument.URL != 'about:blank' && on)
			sorURL = tab.contentDocument.URL;
		// If the new tab the user is looking at hasn't been logged (possibly from turning it off/on) 
		// then it has to be added as a root entry - we have no information about a potential source.
		if (!logHelper.isURLLogged(sorURL) && on) {
			// Note that this will also properly log a tab that has been opened
			// with "open in new tab" due to the first IF clause in logData.log
			sorURL = 'EMPTY_SOURCE_ENTRY';
			destURL = tab.contentDocument.URL;
			logData.log(tab.contentDocument, tab.contentWindow);
		}
	},
	
	/*
	 * Test required conditions that must hold before a website can be logged.
	 * Globals: destURL, on, sorURL
	 * @param {Event} aEvent
	 */
	preLog: function(aEvent) {
		destURL = content.document.URL;
		if (on  && !(destURL == sorURL) && !(destURL == 'about:blank'))
			logData.log(content.document, content.window);
	}
}

/*
 * Initialization:
 *	Add appropriate listeners to the window to control the main functionality of the logging process.
 */
window.addEventListener(
  "load",
  function () {
    gBrowser.addEventListener("pageshow", logData.preLog, true);
	var container = gBrowser.tabContainer;
	container.addEventListener("TabSelect", logData.tabChange, false);
  },
  false
);